package com.kotlin.book.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.kotlin.book.R
import com.kotlin.book.databinding.ItemReadDirectoryBinding
import com.kotlin.book.entry.Chapter

class ReadDirectoryItemAdapter(
    private var itemList: List<Chapter>,
    private var currentIndex: Int = 0,
    private val callback: (Int) -> Unit
) :
    RecyclerView.Adapter<ReadDirectoryItemAdapter.ItemViewHolder>() {
    var isSort = false
    class ItemViewHolder(itemBinding: ItemReadDirectoryBinding) :
        RecyclerView.ViewHolder(itemBinding.root) {

        val chapterName: TextView = itemBinding.chapterName
        val chapterTime: TextView = itemBinding.chapterTime
        val chapterWord: TextView = itemBinding.chapterWord
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
        val binding =
            ItemReadDirectoryBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ItemViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
        val item = itemList[position]
        holder.chapterName.text = item.name
        holder.chapterTime.text = item.createTime?.substring(0,10)
        holder.chapterWord.text = item.word?.run {
            item.word.toString() + "字"
        }

        var rid = R.color.text_color_primary
        if (currentIndex == position) {
            rid = R.color.primary_color
        }
        holder.chapterName.setTextColor(
            ContextCompat.getColor(
                holder.itemView.context,
                rid
            )
        )
        holder.itemView.setOnClickListener {
            if(isSort){
                callback(itemList.size-1-holder.adapterPosition)
            }else{
                callback(holder.adapterPosition)
            }
        }
    }

    override fun getItemCount(): Int {
        return itemList.size
    }

    fun setIndex(index: Int) {
        currentIndex = index
        if(isSort){
            currentIndex = itemList.size-1-currentIndex
        }
        notifyDataSetChanged()
    }

    fun setSort() {
        isSort = !isSort
        if(isSort){
            currentIndex = itemList.size-1-currentIndex
        }
        itemList = itemList.toList().reversed()
        notifyDataSetChanged()
    }
}